package com.wjj.getip.job;

import com.wjj.getip.utils.UpdateRecordModify;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Component
@Slf4j
public class UpdateIP {
    @Autowired
    private UpdateRecordModify updateRecordModify;
    @Autowired
    private RedisTemplate redisTemplate;
    //子域名为www的recordId(subDomain)
    @Value("${private.TYPE4WWWID}")
    private String WWW;
    //子域名为@的recordId(subDomain)
    @Value("${private.TYPE4AID}")
    private String A;

    @Scheduled(cron = "0 */1 * * * ?")
    private void getIP() {
        Process exec = null;
        try {
            exec = Runtime.getRuntime().exec("curl ifconfig.me");
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        String newIP = dealProcess(exec);
        Object oldIP = redisTemplate.opsForValue().get("ip");
        if (newIP != null && (oldIP == null || !newIP.equals(oldIP.toString()))) {
            log.warn("IPchanged!!! oldIP: " + oldIP + " -> newIP: " + newIP);
            updateIP(newIP);
        }
    }

    private void updateIP(String newIP) {
        redisTemplate.opsForValue().set("ip", newIP);
        updateRecordModify.update(WWW, newIP,"www");
        updateRecordModify.update(A, newIP,"@");
    }

    private static String dealProcess(Process exec) {
        InputStream in = null;
        BufferedReader reader = null;
        try {
            in = exec.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder builder = new StringBuilder();
            String ip;
            while ((ip = reader.readLine()) != null) {
                builder.append(ip);
            }
            return builder.toString();
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (reader != null) {
                    reader.close();
                }
                exec.destroy();
            } catch (Exception e) {
            }
        }
    }
}
